package promote.brozen.dubbo.consumers.javaconfig;

import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.*;
import org.apache.dubbo.config.bootstrap.builders.ConsumerBuilder;
import promote.brozen.dubbo.interfaces.api.UserApi;
import promote.brozen.dubbo.interfaces.beans.User;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.LockSupport;

/**
 * @author Brozen
 * @date 2020/9/9 11:13 AM
 * @email brozen@qq.com
 */
public class JavaReferencer {

    private ApplicationConfig applicationConfig;

    private RegistryConfig registryConfig;

    private ProtocolConfig protocolConfig;

    private ConsumerConfig consumerConfig;

    private Map<String, ReferenceConfig<?>> services;

    public JavaReferencer() {

        // Application的配置可以参考 http://dubbo.apache.org/zh-cn/docs/user/references/xml/dubbo-application.html
        applicationConfig = new ApplicationConfig();
        applicationConfig.setName("TestExportApiWithJavaConfig");

        // http://dubbo.apache.org/zh-cn/docs/user/references/xml/dubbo-registry.html
        registryConfig = new RegistryConfig();
        registryConfig.setAddress("nacos://127.0.0.1:8848?namespace=484a0ac6-add3-4ea8-847d-cdefec40f5b8");
        registryConfig.setProtocol("nacos");
        registryConfig.setGroup("dev");

        // 服务提供者协议，http://dubbo.apache.org/zh-cn/docs/user/references/xml/dubbo-protocol.html
        protocolConfig = new ProtocolConfig();
        protocolConfig.setName("dubbo");
        protocolConfig.setPort(30010);
        protocolConfig.setThreads(2);

        // Provider的配置
        consumerConfig = new ConsumerBuilder()
                .application(applicationConfig)
                .addRegistry(registryConfig)
                .build();

        services = new ConcurrentHashMap<>();
    }

    public UserApi referenceUserApi() {
        ReferenceConfig<UserApi> userApiRef = new ReferenceConfig<>();
        userApiRef.setConsumer(consumerConfig);
        userApiRef.setInterface(UserApi.class);
        userApiRef.setVersion("0.0.1");
        userApiRef.setGroup("brozen");
        services.put("userApi", userApiRef);
        return userApiRef.get();
    }


    public static void main(String[] args) {
        JavaReferencer javaReferencer = new JavaReferencer();
        UserApi userApi = javaReferencer.referenceUserApi();

        User user = new User();
        user.setMail("1bb@qq.com");
        user.setNick("1bb");
        user.setPassword("1bbpp");
        userApi.createUser(user);

        long id = RandomUtils.nextLong();
        user = new User();
        user.setUserId(id);
        user.setMail("k999@qq.com");
        user.setNick("K999");
        user.setPassword("k999pp");
        userApi.createUser(user);

        User u = userApi.getUser(id);
        System.out.println(u);
        System.out.println(userApi.listUser());
        LockSupport.park();

    }
}
